package com.fms.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fms.common.vo.Result;
import com.fms.sys.entity.Card;
import com.fms.sys.service.ICardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.fms.common.utils.JwtUtils;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Jinfeng
 * @since 2023-03-18
 */
@RestController
@RequestMapping("/card")
@Validated
public class CardController {

    @Autowired
    private ICardService cardService;

    @GetMapping("/list")
    public Result<Map<String, Object>> getCardList(
            @RequestParam(value = "cardNumber", required = false) String cardNumber,
            @RequestParam(value = "pageNo", defaultValue = "1") Long pageNo,
            @RequestParam(value = "pageSize", defaultValue = "10") Long pageSize) {

        LambdaQueryWrapper<Card> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(cardNumber), Card::getCardNumber, cardNumber);
        wrapper.orderByDesc(Card::getCreateTime);

        Page<Card> page = new Page<>(pageNo, pageSize);
        cardService.page(page, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", page.getRecords());

        return Result.success(data);
    }

    @PostMapping
    public Result<?> addCard(@Valid @RequestBody Card card) {
        // 获取当前登录用户ID
        Long userId = JwtUtils.getCurrentUserId();
        card.setUserId(userId);
        cardService.save(card);
        return Result.success("新增银行卡成功");
    }

    @PutMapping
    public Result<?> updateCard(@Valid @RequestBody Card card) {
        // 获取当前登录用户ID
        Long userId = JwtUtils.getCurrentUserId();
        card.setUserId(userId);
        cardService.updateById(card);
        return Result.success("修改银行卡成功");
    }

    @GetMapping("/{id}")
    public Result<Card> getCardById(@PathVariable("id") Long id) {
        Card card = cardService.getById(id);
        if (card == null) {
            return Result.fail("银行卡不存在");
        }
        return Result.success(card);
    }

    @DeleteMapping("/{id}")
    public Result<?> deleteCardById(@PathVariable("id") Long id) {
        if (!cardService.removeById(id)) {
            return Result.fail("删除失败，银行卡不存在");
        }
        return Result.success("删除银行卡成功");
    }
}
